<!--考试安排-->
<template>
  <h4>考试安排</h4>
  <el-divider/>
  <el-container>
    <el-main>
      <!-- 动态表格展示考试数据 -->
      <el-table
          :data="examList"
          style="width: 100%; margin-top: 20px;"
          border
          stripe
          :default-expand-all="false"
      >

        <el-table-column type="index" label="序号" width="100px" align="center"/>
        <el-table-column prop="id" label="考试ID" width="300px" align="center" show-overflow-tooltip/>
        <el-table-column prop="startTime" label="预计考试开始时间" width="300px" align="center"/>
        <el-table-column prop="name" label="考试名称" width="200px" align="center"/>
        <el-table-column prop="subject" label="科目" width="150px" align="center"/>
        <el-table-column prop="teacherName" label="教师" width="150px" align="center"/>
        <el-table-column prop="totalScore" label="总分" width="150px" align="center"/>
        <el-table-column prop="objectiveScore" width="150px" label="客观题得分" align="center"/>
        <el-table-column prop="subjectiveScore" width="150px" label="主观题得分" align="center"/>
        <!--        <el-table-column prop="createTime" label="创建时间" width="300px" align="center" />-->

        <!-- 操作列 -->
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" v-if="scope.row.state == 2" type="primary" plain @click="handleDelete(scope.row)">
              开始考试
            </el-button>
            <el-button size="small" disabled v-if="scope.row.state == 1" type="info" plain>等待中</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import {onMounted, ref, onUnmounted, reactive} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {allTesData} from '../api/tesPaper/tesPaper.ts';
import {queryClassData} from '../api/class/class.ts';
import {useUserStore} from '../stores/userStore.ts';
import {v4 as uuidv4} from 'uuid';
import {selectIdAndData} from '../api/user/user.ts';
import {saveStudentPaper} from '../api/sysStudentAnswerSheet/sysStudentAnswerSheet.ts';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';

const router = useRouter();

dayjs.locale('zh-cn');

// 获取当前用户信息
const userStore = useUserStore();

const examList = ref<any[]>([]);
let dataRefreshTimer: number | null = null; // 用于存储定时器的ID

function getData(){
  allTesData().then(res => {
    examList.value = res.data
    console.log(res.data)
  }).catch(e => {
    ElMessage.error(e.message)
  })
}


onMounted(() => {

  getData(); // 立即获取一次数据
  // 设置定时器，每30秒刷新一次数据
  dataRefreshTimer = window.setInterval(() => {
    getData();
  }, 5000); // 30000毫秒 = 30秒
  userDate()
});

// 【重要】组件卸载时，必须清除定时器，否则会造成内存泄漏
onUnmounted(() => {
  if (dataRefreshTimer) {
    clearInterval(dataRefreshTimer);
    dataRefreshTimer = null;
  }
});

// 判断是否在考试班级范围
function isInExamClass(examId: number, classId: Array<number>) {
  let is = false;
  classId.forEach((id: any) => {
    if (id === examId) {
      console.log("在考试班级范围")
      is = true;
      return;
    }
  })
  return is;
}

// 当前用户信息
const userData = reactive({
  age: undefined,
  createTime:"",
  gender: "",
  id: undefined,
  imgUrl:"",
  name: "",
  password: "",
  router: "",
  studengOrteacherId: undefined,
  token: "",
  updateTime: "",
  username: "",
})

function userDate(){
  selectIdAndData(userStore.userInfo.studengOrteacherId).then(res => {
    console.log("用户信息",res.data)
    userData.age = res.data.age;
    userData.createTime = res.data.createTime;
    userData.gender = res.data.gender;
    userData.id = res.data.id;
    userData.imgUrl = res.data.imgUrl;
    userData.name = res.data.name;
    userData.password = res.data.password;
    userData.router = res.data.router;
    userData.studengOrteacherId = res.data.studengOrteacherId;
    userData.token = res.data.token;
    userData.updateTime = res.data.updateTime;
    userData.username = res.data.username;
  }).catch(e => {
    ElMessage.error(e.message)
  })
}



// 创建答题卡
async function createAnswerSheet(row: any) {
  userDate();
  const sysStudentAnswerSheet = {
    id: uuidv4(), // 答题卡 ID (类型已修改为 string)
    tesPaperId: row.id, // 试题 ID (类型已修改为 string)
    tesPaperName: row.name, // 试题名称
    studentId: userData.studengOrteacherId, // 学生 ID
    studentName: userData.name, // 学生姓名
    teacherId: row.teacherId, // 教师 ID
    teacherName: row.teacherName, // 教师姓名
    subject: row.subject, // 科目
    content: row.content, // 答题内容
    objectiveTestScores: undefined, // 客观题得分
    subjTestScores: undefined, // 主观题得分
    totalScores: undefined, // 总得分
    createTime: dayjs().format('YYYY年MM月DD日 HH:mm:ss'), // 创建时间 (开始答题时间)
    testStartTime: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
    endTime: "", // 结束时间 (提交试卷时间)
    timeTaken: "", // 用时 (例如: "01:30:25")
    timeLimit: row.timeLimit, // 时间限制 (例如: "01:30:25")
    state: undefined,   // 状态(1: 等待/未开始, 2: 进行中, 3: 已完成)
  }
  console.log("创建答题卡", sysStudentAnswerSheet)
  await saveStudentPaper(sysStudentAnswerSheet).then(_ => {
    ElMessage({
      type: 'success',
      message: '创建答题卡成功',
    })
  }).catch(e => {
    ElMessage.error(e.message)
  })
  router.push({
    path: '/main/takeExam',
    query: {id: sysStudentAnswerSheet.id,}
  })
}

// 提示框
async function alerts(row: any) {
  ElMessageBox.confirm(
      '是否开始考试?',
      'Warning',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  )
      .then(() => {
        createAnswerSheet(row)
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}

// 开始考试
const handleDelete = async (row: any) => {
  const obj = {
    id: row.class,
  }
  let is: boolean = false;
  await queryClassData(obj).then(res => {
    console.log("判断是否在考试班级范围", res.data)
    if (res.data[0].studentId.length != 0) {
      console.log(res.data[0].studentId)
      console.log(userStore.userInfo.studengOrteacherId)
      is = isInExamClass(userStore.userInfo.studengOrteacherId, res.data[0].studentId)
    }
  }).catch(e => {
    console.log(e)
  })
  if (is) {
    await alerts(row)
  } else {
    await ElMessageBox.alert('非常抱歉，您不在考试班级范围内', 'Title', {
      confirmButtonText: 'OK',
      type: 'info',
    })
  }
};

</script>

<style scoped lang="scss">
.el-header {
  padding: 20px;
}

// 题目详情展开区域的样式
.exam-content-wrapper {
  padding: 10px 20px;
  background-color: #fafafa;
  border-radius: 4px;

  h4 {
    margin: 0 0 15px 0;
    color: #409eff;
  }
}

.question-item {
  margin-bottom: 15px;

  .el-card {
    border: 1px solid #ebeef5;
  }
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .question-type {
    font-weight: bold;
    color: #606266;
  }

  .question-score {
    color: #e6a23c;
    font-weight: bold;
  }
}

.question-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.options-list {
  .el-radio {
    display: block;
    margin-bottom: 10px;
    margin-left: 20px; // 缩进选项
    &.correct-option {
      color: #67c23a; // 正确答案用绿色高亮
      font-weight: bold;
    }
  }
}

.reference-answer {
  margin-top: 10px;

  p {
    margin: 0;
  }
}
</style>
